import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, execjs
from common.helper import Helper
from urllib.parse import urlencode
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "i康保老年医疗"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(45, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保额
                "money": ["2000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费方式
                "payType": ["年交"],
                # 质子重离子医疗保险金额
                "extSerious": ["0", "1000000"],
                # 恶性肿瘤保险金额
                "cancerMedical": ["0", "1500000"],
                # 意外伤害保险金额
                "accidentDeath": ["0", "1205000"],
                # 产品计划
                "plan": ["普惠版", "特需版"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(61, 71)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保额
                "money": ["2000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费方式
                "payType": ["年交"],
                # 质子重离子医疗保险金额
                "extSerious": ["0", "1000000"],
                # 恶性肿瘤保险金额
                "cancerMedical": ["0"],
                # 意外伤害保险金额
                "accidentDeath": ["0", "1205000"],
                # 产品计划
                "plan": ["普惠版", "特需版"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["money"], plan[k]["expire"],
                             plan[k]["payType"], plan[k]["extSerious"], plan[k]["cancerMedical"],
                             plan[k]["accidentDeath"], plan[k]["plan"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # date_to_timestamp
    def dateToTimestamp(self, date=None):
        js = '''
        function getUnixTime(dateStr){
                var newstr = dateStr.replace(/-/g,'/'); 
                var date =  new Date(newstr); 
                var time_str = date.getTime().toString();
                return time_str
                
            }
        '''
        cxt = execjs.compile(js)
        timestamp = cxt.call("getUnixTime", date)

        timestamp = int(int( timestamp ) / 1000)

        return timestamp

    # 执行爬虫v
    def requestJson(self, dt=None):

        if (dt["extSerious"] == "0" and dt["cancerMedical"] == "0" and dt["accidentDeath"] == "0"):
            print("/***********************/")
            date = str(int(2020 - int(dt["year"]))) + "-01-01 08:00:00"
            timestamp = self.dateToTimestamp(date)

            if dt["plan"] == "普惠版":
                planCode = "995"
            else:
                planCode = "1003"
            data = {

                "insId": "87",
                "insPlanId": planCode,
                "birthDay": timestamp,
                "hasSocialSecurity": "2" if dt["socialSec"] == "N" else "1",
            }
            print( data )
            payload = urlencode(data).replace("+", "")
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
            if r.status_code == 200 and "成功" in r.text:
                price = r.json()["data"]["price"].split("|")[0]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                print( data )
                self.mysql.updatePrice( data )
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state":3
                }
                self.mysql.updateTask( data )
                print("\n/*更新产品价格数据失败:%d*/"%dt["id"])



        else:
            date = str(int(2020 - int(dt["year"]))) + "-01-01 08:00:00"
            timestamp = self.dateToTimestamp(date)
            if dt["plan"] == "普惠版":
                planCode = "995"
            else:
                planCode = "1003"
            empty = ""
            df = {
                "extSerious": "9" if dt["extSerious"] != "0" else "",
                "cancerMedical": "3" if dt["cancerMedical"] != "0" else "",
                "accidentDeath": "10" if dt["accidentDeath"] != "0" else ""
            }
            items = [ v for v in df.values() ]

            if ( items.count("") > 1):
                print("/**********|**********/")
                for index in items:
                    if index != "":
                        duty = index
                        data = {

                            "insId": "87",
                            "insPlanId": planCode,
                            "birthDay": timestamp,
                            "hasSocialSecurity": "2" if dt["socialSec"] == "N" else "1",
                            "dutyIds": duty
                        }
                        print( data )
                        payload = urlencode(data).replace("+", "")
                        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                          data=payload)
                        if r.status_code == 200 and "成功" in r.text:

                            price = r.json()["data"]["price"].split("|")[0]
                            data = {
                                "name": self.name,
                                "id": dt["id"],
                                "price": price
                            }
                            print(data)
                            self.mysql.updatePrice(data)
                        else:
                            data = {
                                "name": self.name,
                                "id": dt["id"],
                                "state": 3
                            }
                            self.mysql.updateTask(data)
                            print("\n/*更新产品价格数据失败:%d*/" % dt["id"])

                    else:
                        pass

            else:
                print("/**********||**********/")
                for v in df.values():
                    empty +="{0}|".format( v )

                result =  empty.strip("|")

                duty = result if "||" not in result else result.replace("||","|")
                data = {

                    "insId": "87",
                    "insPlanId": planCode,
                    "birthDay": timestamp,
                    "hasSocialSecurity": "2" if dt["socialSec"] == "N" else "1",
                    "dutyIds": duty
                }
                print( data )
                payload = urlencode(data).replace("+", "")
                r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                  data=payload)
                if r.status_code == 200 and "成功" in r.text:
                    price = r.json()["data"]["price"].split("|")[0]
                    data = {
                        "name": self.name,
                        "id": dt["id"],
                        "price": price
                    }
                    print(data)
                    self.mysql.updatePrice(data)
                else:
                    data = {
                        "name": self.name,
                        "id": dt["id"],
                        "state": 3
                    }
                    self.mysql.updateTask(data)
                    print("\n/*更新产品价格数据失败:%d*/" % dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            print(dt)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
